const vipEl = document.createElement('div');
vipEl.id = 'vipPop';
vipEl.className = "bg hid";
vipEl.innerHTML = '<div class="vip-pop pop-box">' +
    '                   <div class="vip-left">' +
    '                       <div class="pop-content">' +
    '                           <p>亲爱的MBA智库百科用户：</p>' +
    '                           <hr/>' +
    '                           <p>过去的17年，百科频道一直以免费公益的形式为大家提供知识服务，这是我们团队的荣幸和骄傲。\n\n' +
    '                           然而，在目前越来越严峻的经营挑战下，单纯依靠不断增加广告位来维持网站运营支出，必然会越来越影响您的使用体验，这也与我们的初衷背道而驰。\n\n' +
    '                           因此，经过审慎地考虑，我们决定推出VIP会员收费制度，以便为您提供更好的服务和更优质的内容。</p>' +
    '                           <hr/>' +
    '                           <p style="font-weight: bold;color: #fff;">MBA智库百科VIP会员，您的权益将包括：\n' +
    '                           1、无广告阅读；\n' +
    '                           2、免验证复制。</p>' +
    '                           <hr/>' +
    '                           <p>当然，更重要的是长期以来您对百科频道的支持。诚邀您加入MBA智库百科VIP会员，共渡难关，共同见证彼此的成长和进步！</p>' +
    '                           <hr/>' +
    '                           <hr/>' +
    '                           <div>MBA智库百科项目组</div>' +
    '                           <div>2023年8月10日</div>' +
    '                       </div>' +
    '                    </div>' +
    '                    <div class="vip-right" style="width: 640px">' +
    '                       <div class="vip-head">' +
    '                           <div class="vip-title">' +
    '                               <span class="title-left">百科VIP</span>' +

    '                               <a href="javascript:void(0)" class="title-right">' +
    '                                   <div class="avatar-img">' +
    '                                       <img src="" alt="">' +
    '                                   </div>' +
    '                                   <span class="user-name"></span>' +
    '                                   <span class="vip-time"></span>' +
    '                               </a>' +
    '                           </div>' +

    '                           <div class="vip-interests">' +
    '                               <div class="">' +
    '                                   <img src="' + getServer('img') + '/wiki/MBALib/images/ic_cjb.png" alt="">' +
    '                                   无广告阅读' +
    '                               </div>' +
    '                               <div class="">' +
    '                                   <img src="' + getServer('img') + '/wiki/MBALib/images/ic_gznr.png" alt="">' +
    '                                   免验证复制' +
    '                               </div>' +
    '                           </div>' +

    '                           <svg id="vipOffBtn" class="vip-icon" aria-hidden="true">' +
    '                               <use xlink:href="#ic_close"></use>' +
    '                           </svg>' +
    '                       </div>' +

    '                       <div class="vip-open">' +
    '                           <div class="pay-type" id="">' +
    '                               <div class="type-name">支付方式：</div>' +
    '                               <div class="type-box select" data-type="weixin_native">' +
    '                                   <img src="' + getServer('img') + '/doc/images/pay/pay_weixin.png" alt="">' +
    '                                   微信支付' +
    '                               </div>' +
    '                               <div class="type-box" data-type="alipay">' +
    '                                   <img src="' + getServer('img') + '/doc/images/pay/pay_alipay.png" alt="">' +
    '                                   支付宝' +
    '                               </div>' +
    '                               <div class="type-box" data-type="paypal">' +
    '                                   <img src="' + getServer('img') + '/doc/images/pay/pay-paypal.png" alt="">' +
    '                                   PayPal' +
    '                               </div>' +
    '                           </div>' +

    '                           <div class="type-main wechat">' +
    '                               <div id="wechatQr" class="type-qr"></div>' +
    '                               <div class="type-content">' +

    '                                   <div class="content-box">' +
    '                                       <div class="content-left">购买数量：</div>' +
    '                                       <div class="content-right num-btns">' +
    '                                           <button class="no" data-name="minus">-</button>' +
    '                                           <div class="">1</div>' +
    '                                           <button class="" data-name="add">+</button>' +
    '                                       </div>' +
    '                                   </div>' +

    '                                   <div class="content-box">' +
    '                                       <div class="content-left">应付金额：</div>' +
    '                                       <div class="content-right pay-name"><span>10</span>元</div>' +
    '                                   </div>' +

    '                                   <div class="content-box paypal-rate hid">' +
    '                                       <div class="content-left">汇率换算：</div>' +
    '                                       <div class="content-right pay-name paypal-box">' +
    '                                           <span>10</span>' +
    '                                           <div class="rate-box">' +
    '                                               <div>美元(USD)</div>' +
    '                                               <svg class="arrow-icon" aria-hidden="true">' +
    '                                                   <use xlink:href="#ic_arrow_down"></use>' +
    '                                               </svg>' +
    '                                               <ul id="currency" class="hid">' +
    '                                                   <li class="option checked" data-type="usd">美元(USD)</li>' +
    '                                                   <li class="option" data-type="cad">加元(CAD)</li>' +
    '                                                   <li class="option" data-type="jpy">日元(JPY)</li>' +
    '                                                   <li class="option" data-type="gbp">英镑(GBP)</li>' +
    '                                                   <li class="option" data-type="eur">欧元(EUR)</li>' +
    '                                                   <li class="option" data-type="aud">澳元(AUD)</li>' +
    '                                               </ul>' +
    '                                           </div>' +
    '                                           <div class="right-tips">' +
    '                                               <p>按当月汇率换算，</p>' +
    '                                               <p>包含手续费</p>' +
    '                                           </div>' +
    '                                       </div>' +
    '                                   </div>' +

    '                                   <div class="wechat-tips content-box">' +
    '                                       <svg class="qr-icon" aria-hidden="true">' +
    '                                           <use xlink:href="#ic_scan"></use>' +
    '                                       </svg>' +
    '                                       打开手机微信  扫一扫继续付款' +
    '                                   </div>' +
    '                               </div>' +
    '                               <div class="type-btn">立即开通</div>' +
    '                           </div>' +

    '                           <div class="pop-tips paypal-tips">' +
    '                               PayPal支付后，可能会遇到VIP权益未及时开通的情况，请您耐心等待，或者联系百科微信客服：mbalib888。' +
    '                           </div>' +

    '                           <div class="pop-tips">' +
    '                               温馨提示：当无法进去支付页面时，可刷新后重试或更换浏览器<br/>' +
    '                               开通百科会员即视为同意<a class="" href="' + getServer('passport') + '/protocol?type=wiki_vip" target="_blank">《MBA智库·百科会员服务规则》</a>' +
    '                           </div>' +
    '                       </div>' +
    '                       <form id="form_starPay" style="display:none;" name="form_starPay" target="_blank" style="display:none" action="https://www.paypal.com/cgi-bin/webscr" method="post"><code class="html comments"><!--测试www.sandbox.paypal.com，正式www.paypal.com--></code>' +
    '                           <input type="hidden" name="cmd" value="_xclick">' +
    '                           <input type="hidden" name="business" value="">' +
    '                           <input type="hidden" name="item_name" value="">' +
    '                           <input type="hidden" name="amount" value="">' +
    '                           <input type="hidden" name="currency_code" value="">' +
    '                           <input type="hidden" name="return" value="">' +
    '                           <input type="hidden" name="notify_url" value="">' +
    '                           <input type="hidden" name="invoice" value="">' +
    '                           <input type="hidden" name="custom" value="">' +
    '                           <input type="hidden" name="lc" value="">' +
    '                       </form>' +

    '                   </div>' +
    '                   </div>';

const successEl = document.createElement('div');
successEl.id = 'successPop';
successEl.className = 'bg hid';
successEl.innerHTML = ' <div class="pop-box success-pop">' +
    '                       <div class="pop-head">' +
    '                           <svg id="successOffBtn" class="head-icon" aria-hidden="true" onclick="$(\'#successPop\').fadeOut();location.reload();">' +
    '                               <use xlink:href="#ic_close"></use>' +
    '                           </svg>' +
    '                       </div>' +
    '                       <div class="success-box">' +
    '                           <svg class="success-icon" aria-hidden="true">' +
    '                               <use xlink:href="#ic_success_filled"></use>' +
    '                           </svg>' +
    '                           <h3 class="success-title">支付成功</h3>' +
    '                           <button class="success-btn" onclick="$(\'#successPop\').fadeOut();location.reload();">完成</button>' +
    '                       </div>' +
    '                   </div>';

var token = wfGetCookie("wikidbAccessToken");

var UserInfo = (function () {
    var instance;

    function init() {
        var user = null;

        function getUserinfo(callback) {
            $.ajax({
                type: 'get',
                url: getServer('www') + "/wikivip/userinfo",
                data: { access_token: token },
                dataType: 'json',
                xhrFields: { withCredentials: true },
                crossDomain: true,
                success: function (result) {
                    freshUserInfo(result, getUserinfo, function (data) {
                        user = data;

                        let str = '';
                        if (user.is_vip) {
                            str = user.vip_expire.split(' ')[0] + '&nbsp;前有效';
                        } else if (user.vip_expire) {
                            str = '已失效';
                        } else {
                            str = '未开通';
                        }
                        $('.vip-time').html(str)
                        $('#pt-vip a').html('百科VIP：' + str);
                        if (typeof (callback) == 'function') {
                            callback(data); // 异步操作成功时，调用 callback 并传递结果
                        }
                    })
                }
            });
        }

        function gainUser(callback) {
            let isUser = {
                is_vip: 0,
                username: '未登录',
                vip_expire: '',
                avatar: getServer('img') + '/passport/images/user-100.jpg',
            };

            if (token && user) {
                isUser = user;
            } else if (token) {
                getUserinfo(function (user) {
                    callback(user); // 使用回调函数中获取的用户对象返回异步参数
                    let loginOnOpen = wfGetCookie('loginOnOpen');
                    if (loginOnOpen && user.is_vip == 0) {
                        wfDeleteCookie('loginOnOpen', '.mbalib.com');
                        setTimeout(function () {
                            let vipPayInstance = VipPay.getInstance();
                            vipPayInstance.popupInit(loginOnOpen);
                            vipPayInstance.showVipPop();
                        }, 1000);
                    }
                });
                return;
            }

            $('.user-name').html(isUser.username);
            $('.avatar-img img').attr('src', isUser.avatar);
            // return new Promise(function (resolve, reject) {
            //     resolve(isUser);
            // });
            // return isUser;
            callback(isUser);
        }

        return {
            // 公共方法和属性
            getUser: gainUser,
            updataUser: getUserinfo,
        };
    }

    return {
        // 获取单例实例的方法
        getInstance: function () {
            if (!instance) {
                instance = init();
            }
            return instance;
        },
    };
})();

var VipPay = (function () {
    var instance; // 保存单例实例

    function init() {
        var type = 'weixin_native'; // 支付类型
        var cardKey = null; // 需要的支付信息
        var timeId = null; // 延时器
        var vipName = 1; // 购买数量
        var priceInitial = 0; // 初始金额
        var price = 0; // 支付金额
        var from_source = null; // 支付来源
        var paypalList = null; // PayPal换算比例
        var paypalType = 'usd'; // PayPal换算比例
        var _this = this;
        document.body.appendChild(vipEl);
        document.body.appendChild(successEl);

        var userInfoInstance = UserInfo.getInstance();

        // 点击微信
        function setWechatQr() {
            $('.type-btn').hide();
            $('.paypal-rate').hide();
            $('.paypal-tips').hide();

            if (!token) {
                $('.type-main').addClass('wechat');
                $('#wechatQr').show();
                $('.wechat-tips').show();
                $('#wechatQr').html('<img src="' + getServer('img') + '/doc/images/pay/no_login.png" />');
                return;
            }

            if (price > 0) {
                $('.type-main').addClass('wechat');
                $('#wechatQr').show();
                $('.wechat-tips').show();
                $('#wechatQr').html('');
                createorder();
            } else {
                setAlipay();
            }

        }

        // 点击支付宝
        function setAlipay() {
            $('.type-btn').show();
            $('.type-main').removeClass('wechat');
            $('#wechatQr').hide();
            $('.wechat-tips').hide();
            $('.paypal-rate').hide();
            $('.paypal-tips').hide();
        }

        // 点击PayPal
        function setPayPal() {
            $('.type-btn').show();
            $('.type-main').addClass('wechat');
            $('#wechatQr').hide();
            $('.wechat-tips').hide();
            $('.paypal-rate').show();
            $('.paypal-tips').show();
        }

        function setPrice() {
            price = roundNumber(priceInitial * vipName);
            $('.content-right.pay-name span').html(price);
            if (paypalList) {
                selectPaypal();
            }
        }

        function createorder() {
            let qsData = {
                access_token: token,
                key: cardKey,
                pay_type: type,
                num: vipName,
            };

            if (type == 'paypal') {
                qsData.currency = paypalType;
            }

            if (from_source) {
                /**
                 * 来源
                 * 一封信弹窗： letter_pop
                 * 阅读到底部： read_end
                 * 顶部导航栏： top menu
                 * 复制弹窗： copy_pop
                 * VIP广告弹窗： ad_VIP_pop
                 */
                qsData.from_source = from_source;
            }

            $.ajax({
                type: 'POST',
                url: getServer('www') + "/wikivip/createorder",
                data: qsData,
                dataType: 'json',
                xhrFields: { withCredentials: true },
                crossDomain: true,
                success: function (result) {
                    freshUserInfo(result, createorder, createorderSuccess);
                },
                error: function (error) {
                }
            });
        }

        function getPayoption() {
            $.ajax({
                type: 'get',
                url: getServer('www') + "/wikivip/payoption",
                data: {},
                dataType: 'json',
                xhrFields: { withCredentials: true },
                crossDomain: true,
                success: function (result) {
                    freshUserInfo(result, getPayoption, setVipCard);

                },
                error: function (error) {
                }
            });
        }

        function getPaypal() {
            $.ajax({
                type: 'get',
                url: getServer('www') + "/api/paypal",
                data: {
                    t: Math.random()
                },
                dataType: 'json',
                xhrFields: { withCredentials: true },
                crossDomain: true,
                success: function (result) {
                    paypalList = result;

                    selectPaypal();
                },
                error: function (error) {
                }
            });
        }

        function setVipCard(data) {
            let result = data.data;
            // let result = [
            //     {
            //         "key": "vip",
            //         "title": "1年",
            //         "describe": "开春有礼",
            //         "price": "0.01",
            //         "days": 365
            //     },
            //     {
            //         "key": "vip1",
            //         "title": "6年",
            //         "describe": "开春有礼",
            //         "price": "0",
            //         "days": 666
            //     },
            //     {
            //         "key": "vip2",
            //         "title": "3年",
            //         "describe": "开春有礼",
            //         "price": "888",
            //         "days": 188
            //     },
            // ];

            if (result && result.length) {
                for (let i = 0; i < result.length; i++) {
                    let cardEl = document.createElement('div');
                    if (!cardKey) {
                        // 默认为第一个支付信息
                        cardKey = result[i].key;
                        priceInitial = result[i].price;
                        setPrice();
                        cardEl.className = "vip-card select";
                    } else {
                        cardEl.className = "vip-card";
                    }
                    cardEl.setAttribute('data-price', result[i].price);
                    cardEl.setAttribute('data-key', result[i].key);

                    cardEl.innerHTML = '<div class="card-left">' +
                        '                   <div class="card-title">' + result[i].title + '</div>' +
                        (result[i].describe ? '                   <div class="card-describe">' + result[i].describe + '</div>' : '') +
                        '               </div>' +
                        '               <div class="card-right">' +
                        '                   <div class="card-price">&yen;&nbsp;<span>' + roundNumber(result[i].price) + '</span></div>' +
                        // '                   <div class="card-originalPrice">&yen;&nbsp;' + result[i].days + '</div>' +
                        '               </div>';
                    $('.pay-type').before(cardEl);
                }
            }
        }

        function createorderSuccess(data) {
            if (data.errorno) {
                return;
            }

            let orderId = '';

            if (type == 'alipay') {
                orderId = data.order_number;
                // 防止火狐拦截
                setTimeout(function() {
                    window.open(data.payurl, "_blank");
                }, 100);
            } else if (type == 'paypal') {
                orderId = data.data.pay_id
                paypalFromBox(data.data);
            } else {
                orderId = data.sign;
                $('#wechatQr').html('');
                $("#wechatQr").qrcode({
                    // render: "table", //table方式
                    width: 150, //宽度
                    height: 150, //高度
                    text: data.url,// 链接
                    correctLevel: 0,
                });
            }

            ispaid(orderId);
        }

        // PayPal跳转
        function paypalFromBox(data) {
            $("#form_starPay [name='business']").val(data.business);
            $("#form_starPay [name='item_name']").val(data.item_name);
            $("#form_starPay [name='amount']").val(data.amount);
            $("#form_starPay [name='currency_code']").val(data.currency);
            $("#form_starPay [name='return']").val(data.return_);
            $("#form_starPay [name='notify_url']").val(data.notify_url);
            $("#form_starPay [name='invoice']").val(data.pay_id);
            $("#form_starPay [name='custom']").val(data.custom);
            
            // 防止火狐拦截
            setTimeout(function() {
                $("#form_starPay").submit();
            }, 100);
        }

        function ispaid(orderId) {
            let qsData = {};
            if (type == 'alipay' || type == 'paypal') {
                qsData.order = orderId
            } else {
                qsData.sign = orderId
            }

            $.ajax({
                type: 'GET',
                url: getServer('www') + "/wikivip/ispaid",
                data: qsData,
                dataType: 'json',
                xhrFields: { withCredentials: true },
                crossDomain: true,
                success: function (result) {
                    if (timeId) {
                        clearTimeout(timeId);
                    }
                    if (result.state == "success") {
                        userInfoInstance.updataUser(function () { });
                        // $('#vipPop').fadeOut();
                        hideVipPop();
                        $('#successPop').fadeIn();
                    } else {

                        timeId = setTimeout(function () {
                            ispaid(orderId);
                        }, 5000);
                    }
                },
                error: function (error) {
                }
            });
        }

        getPayoption();
        getPaypal();

        function popupInit(from_sources) {
            from_source = from_sources;
            let loginHref = $('#pt-login a').attr('href');
            if (loginHref) {
                $('#vipPop .title-right').attr('href', loginHref);
                $('#vipPop .title-right').click(function (event) {
                    wfSetCookie('loginOnOpen', from_source || 1, 60 * 24, ".mbalib.com");
                })
            } else {
                $('#vipPop .title-right').css('cursor', 'auto');
            }

            if (type == 'alipay') {
                setAlipay();
            } else if (type == 'weixin_native') {
                setWechatQr();
            } else if (type == 'paypal') {
                setPayPal();
            }

            if (!paypalList) {
                getPaypal();
            }

        }

        function showVipPop() {
            if (paypalList) {
                selectPaypal();
            }
            // if (from_source == 'read_end') {
            //     $('#vipPop .vip-left').show();
            // } else {
            //     $('#vipPop .vip-left').hide();
            // }
            $('#vipPop').fadeIn();
            $("html").css({ height: "100%", overflow: "hidden" });
            if (typeof (statWikiPcVipPop) == 'function') {
                statWikiPcVipPop();
            }
        }

        function hideVipPop() {
            if (timeId) {
                clearTimeout(timeId);
            }
            $('#vipPop').fadeOut();
            $("html").css({ height: "auto", overflow: "visible" });
        }

        function selectPaypal() {
            let obj = paypalList[paypalType];
            let money = price * obj.paypal_rate;
            money = money - money * obj.paypal_charge * 0.01;
            $('.paypal-box > span').text(roundNumber(money));
        }

        // PayPal收起
        function useSlideUp() {
            selectPaypal();
            $('#currency').slideUp(150);
            $('.rate-box .arrow-icon').attr('class', 'arrow-icon');
            $(window).off('click', useSlideUp);
        }
        // PayPal展开
        function useSlideDown() {
            $('#currency').slideDown(150);
            $('.rate-box .arrow-icon').attr('class', 'arrow-icon rotate');
            $(window).on('click', useSlideUp);
        }

        $('.rate-box').click(function (event) {
            event.stopPropagation();
            if ($('#currency').css('display') === 'block') {
                useSlideUp();
            } else {
                useSlideDown();
            }
        })

        $('#currency li').click(function (event) {
            event.stopPropagation();
            paypalType = $(this).attr('data-type');
            $('#currency li').removeClass('checked');
            $(this).addClass('checked');
            $('.rate-box > div').text($(this).text());
            useSlideUp();
        })

        $('.type-box').click(function () {
            let dataType = $(this).attr('data-type');
            if (type == dataType) {
                return false;
            }
            type = dataType;
            if (timeId) {
                clearTimeout(timeId);
            }

            if (dataType == 'alipay') {
                setAlipay();
            } else if (dataType == 'weixin_native') {
                setWechatQr();
            } else if (dataType == 'paypal') {
                setPayPal();
            }


            $('.type-box').removeClass('select');
            $(this).addClass('select');
        });

        $('.vip-open').on('click', '.vip-card', function () {
            let dataPrice = $(this).attr('data-price');
            let key = $(this).attr('data-key');
            priceInitial = dataPrice;
            cardKey = key;
            type = 'weixin_native';
            setWechatQr();

            $('.vip-card').removeClass('select');
            $(this).addClass('select');
            setPrice();
            popupInit(from_source);
        })

        $('.type-btn').click(function () {
            if(!token){
                wfSetCookie('loginOnOpen', from_source || 1, 60 * 24, ".mbalib.com");
            }
            createorder();
        });
        $('#wechatQr').click(function () {
            if(!token){
                wfSetCookie('loginOnOpen', from_source || 1, 60 * 24, ".mbalib.com");
            }
            createorder();
        });

        $('#vipOffBtn').click(function () {
            // $('#vipPop').fadeOut();
            hideVipPop();
            if (timeId) {
                clearTimeout(timeId);
            }
        })

        $('.content-right.num-btns').on('click', 'button', function () {
            if ($(this).attr('data-name') == 'add') {
                ++vipName;
                $('.content-right.num-btns button:eq(0)').removeClass('no');
            } else {
                if (vipName <= 1) {
                    $('.content-right.num-btns button:eq(0)').addClass('no');
                } else {
                    --vipName;
                }
            }

            setPrice();
            popupInit(from_source);
            $('.content-right.num-btns div').text(vipName);
        })

        return {
            // 公共方法和属性
            getType: function () {
                return type;
            },
            setType: function (newType) {
                type = newType;
            },
            popupInit: popupInit,
            updateVipCard: getPayoption,
            getUserInstance: userInfoInstance,
            showVipPop: showVipPop, // 开启弹窗
            hideVipPop: hideVipPop, // 关闭弹窗
            from_source: from_source,
        };
    }

    return {
        // 获取单例实例的方法
        getInstance: function () {
            if (!instance) {
                instance = init();
            }
            return instance;
        }
    };
})();